<template>
    <div class="header">
      <div class="headContent">
          <div class="fix">
            <div style="margin: 0 auto;width: 1200px;min-width: 1200px">

                <router-link class="logo" to="/" tag="div" @click.native="headIndex = 'index'">
                  <img  src="../../images/logo.png" alt="">
                  <h1 class="collegeText">国科学院</h1>
                  <h2 class="collegeText">国科学院</h2>
                </router-link>
              <transition name="slide-fade-search" mode="out-in">
                <div style="display: inline-block" v-show="searchFlag">
                  <el-dropdown class="" @command="handleCommand1" placement="bottom" :show-timeout=0 >
                    <div :class="{ 'headLoc': true}">
                      <span><i class="icon-dingwei"></i>{{cityName}}</span>
                      <span class="location" >【切换城市】</span>
                    </div>
                    <el-dropdown-menu slot="dropdown" class="cityMsg"  >
                      <el-dropdown-item class="cities" :command="{id:item.id,name:item.cityName}" v-for="(item,index) in city" :key="index">{{item.cityName}}<span v-if="item.flag" style="color: #ff6252">【推荐城市】</span></el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                  <div class="headNav">
                    <router-link @click.native="headIndex = 'index'" :class="{'headActive': $route.path == '/'}" tag="span" to="/">首页</router-link>
                    <router-link @click.native="headIndex = 'course'" id="qbcourse" onclick="_hmt.push(['_trackEvent', 'allorder', 'click', 'qbcourse'])" :class="{'headActive': $route.name == 'allCourse'}" tag="span" to="/allCourse">全部套餐</router-link>
                    <router-link @click.native="headIndex = 'classMien'"  :class="{'headActive': $route.name == 'classMien'}" tag="span" to="/classMien">班级风采</router-link>
                    <router-link @click.native= goPlanClass :class="{'headActive': $route.name == 'classPlan'}" tag="span" to="">开班计划</router-link>
                    <!-- <router-link @click.native="headIndex = 'testVideo'"  :class="{'headActive':headIndex == 'testVideo'}" tag="span" to="/testVideo">视频播放</router-link> -->
                  </div>
                </div>

              </transition>
              <el-dropdown class="personHover" @command="handleCommand" v-if="isLogin" :show-timeout=0>
                <div style="display: inline-block">
                  <img  @click="toPerson('0')" style="width: 28px;height: 28px;border-radius: 50%;margin-right: 9px" :src="currentUser.photo" alt="">
                  <span  @click="toPerson('0')" :class="{'myperson':true}" ><span>个人中心</span><i class="icon-xiaosan_n"></i></span>
                </div>
                <el-dropdown-menu slot="dropdown" class="personInfo"  >
                  <el-dropdown-item class="myInfo" command="0" @click="toPerson('0')">我的资料</el-dropdown-item>
                  <el-dropdown-item class="myOrder" id="wdorder" onclick="_hmt.push(['_trackEvent', 'myorder', 'click', 'wdorder'])" command="1" @click="toPerson('1')">我的订单</el-dropdown-item>
                  <el-dropdown-item class="myCourse" command="2" @click="toPerson('2')">我的课程</el-dropdown-item>
                  <el-dropdown-item class="exit" command="3" @click="exit()">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <div class="headBtn" v-if="!isLogin">
                <span type="text" style="margin-left: 0" @click="dialogShow('register')">注册</span>
                <span type="text" @click="dialogShow('login')">登录</span>
              </div>
              <span v-show="searchFlag" class="searchCourse" @click="searchCourse" @click.stop><i class="icon-sousuo"></i></span>
              <div class="searchNewsz" v-if="isLogin">
                  <span v-show="searchFlag" class="searchNews" @click="checkNewsList(0)" @click.stop><img class="newsIcon" src="../../images/newsIcon.png"/>
                  <p v-if="unreadmesNumber!=0 && unreadmesNumber < 99" class="newsNumber">{{unreadmesNumber}}</p>
                  <p v-else-if="unreadmesNumber==99" class="newsNumber">{{unreadmesNumber}}</p>
                  <p v-else-if="unreadmesNumber > 99" class="newsNumber">99+</p>
                  </span>
                  <div class="newsFrame">
                    <div class="unreadNews">您有<span>{{unreadmesNumber}}</span>条未读消息</div>
                    <div class="newsList" v-if="unreadmesNumber!='0'">
                      <p  v-for="(item,index) in messageList" :key="index">{{item.content}}</p>
                    </div>
                    <div class="checkAll" @click="checkNewsList('0')">查看全部></div>
                  </div>
              </div>
              <transition name="slide-fade-input" v-on:after-enter="enter" v-on:before-leave="beforeLeave">
                <div class="searchBox" v-show="!searchFlag" @click.stop>
                  <span class="searchClose" @click="searchFlag = true"><i class="icon-guanbianniu1"></i></span>
                  <el-autocomplete
                    ref="sosuoVal"
                    class="inline-input"
                    :class="{widths: isWidth}"
                    v-model="state1"
                    :fetch-suggestions="querySearch"
                    :trigger-on-focus="false"
                    @select="handleSelect"
                    :select-when-unmatched="true"
                  ></el-autocomplete>
                  <span class="searchCourse" @click="iconSearch" id="sousuo" onclick="_hmt.push(['_trackEvent', 'iconsearch', 'click', 'sousuo'])"><i class="icon-sousuo"></i></span>
                </div>
              </transition>

            </div>
        </div>
        <el-dialog
          class="headDialog"
          :close-on-click-modal="false"
          :visible.sync="dialogClose"
          :before-close="handleClose" center>
          <el-dialog
            class="protocol-dialog"
            title="国科学院用户协议"
            :visible.sync="gokContract"
            width="800px"  append-to-body
            :close-on-click-modal="false">
            <contract></contract>
          </el-dialog>
          <div slot="title" :class="registerShow == 'register' || registerShow == 'forget' ? 'topM':''" v-text="title"></div>
          <span v-if="registerShow == 'register'" class="icon-back backLogin" style="" @click="dialogShow(registerStep)"></span>
          <span v-if="registerShow == 'forget'" class="icon-back backLogin" @click="dialogShow('login')"></span>
          <!--<span v-if="registerShow == 'login'" class="register" @click="dialogShow('register')">注册</span>-->
          <div class="leftImg">
            <img src="../../images/denglu_tu.png"/>
          </div>
          <login v-if="registerShow == 'login'"  @forgetPwd="dialogShow" @register="dialogS"></login>
          <register v-if="registerShow == 'register'"  :titleOne.sync="title" :contract.sync="gokContract" @login="dialogShow('login')"></register>
          <forget v-if="registerShow == 'forget'" ></forget>
        </el-dialog>
      </div>

    </div>
</template>



<script>
import login from '../start/login'
import register from '../start/register'
import forget from '../start/forgetPwd'
import contract from '../start/gokContract'
import { mapGetters, mapActions, mapMutations } from 'vuex'
import * as opreate from 'api/getData'
import { solve } from 'plus/location'
import { getToken, removeToken } from "plus/auth"

export default {
  name: "logoheader",
  data() {
    return {
      dialogVisible: false,
      registerShow: 'login',
      title: '登录国科学院',
      flag: true,
      registerStep: 'login',
      toggleMsg: false,
      city: '',
      person: false,
      gokContract: false,
      headIndex: 'index',
      searchFlag:true,
      state1:'',
      state2:'',
      isWidth:false,
      courseList:[],
      results:'',
      messageList:[],
      unreadmesNumber:''
    };
  },
  components: {
    login,
    register,
    forget,
    contract
  },
  props:['searchValue'],
  computed: {
    ...mapGetters([
      'currentUser',
      'isLogin',
      'cityId',
      'cityName',
      'dialogClose',
      'unreadNumber',
    ])
},
  created() {
    this.setDialogClose(false)
    // console.log(this.$route)
  },
  mounted() {
    this.getCity()
    if (!getToken()) {
      this.setUser(null)
    }
    if(this.isLogin){
    this.checkMessage()
    }
  },
  methods: {
    enter: function (el, done) {
      this.isWidth = true
    },
    async getData() {
      await opreate.courselistByCategory('', '', this.cityId).then(res => {
        this.courseList = res.packList
        for (let i = 0; i < this.courseList.length; i++) {
          this.courseList[i].pack.allTimes = 0
          for (let j = 0; j < this.courseList[i].pack.courses.length; j++) {
            this.courseList[i].pack.allTimes = Number(this.courseList[i].pack.allTimes) + Number(this.courseList[i].pack.courses[j].periods)
          }
        }
      })
    },
    beforeLeave(){
      this.isWidth = false
    },
    async querySearch(queryString, cb) {
      // if(queryString.trim() == ''){
      //   return
      // }
      let allCourse = this.courseList;
      let results = queryString ? allCourse.filter(this.createFilter(queryString)) : allCourse;
      this.results = results
      // 调用 callback 返回建议列表的数据
      let formatResult = []
      for (let i=0;i<results.length;i++){
        let item = {}
        item.value = results[i].pack.name
        formatResult.push(item)
      }
      if(cb){
        cb(formatResult)
      }
    },
    createFilter(queryString) {
      return (allCourse) => {
        return (allCourse.pack.name.toLowerCase().indexOf(queryString.toLowerCase()) >= 0);
      };
    },
    handleSelect(item) {
      if(item.value.trim() == ''){
        return
      }
      this.setResultCourse(this.results)
      this.searchFlag = true
      this.$emit('update:searchValue','true')
      this.$router.push({
        path: '/resultCourse',
        query: {
          cityId: this.cityId,
          searchKey: item.value
        }
      })
    },
    iconSearch(){
      let item = {
        value:this.state1
      }
      this.handleSelect(item)
    },
    /*搜索*/
    searchCourse(){
      this.searchFlag = false
      this.$emit('update:searchValue','false')
      // 点击按钮触发搜索焦点
      setTimeout(()=>{
        this.$nextTick(function () {
        //DOM 更新了
        this.$refs.sosuoVal.focus()
        })
      },800)
      
    },
    checkNewsList(flag){
      this.$router.push({
        path:'allNews',
        query:{flag: flag}
      })
    },
    /*退出登录*/
    exit() {
      this.$confirm('点击确定按钮退出当前用户，点击取消按钮返回；', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(() => {
        removeToken()
        this.setUser(null)
        this.$router.push({ path: '/home' })
        this.headIndex = 'index'
      }).catch(() => {
      });
    },
    handleCommand(command) {
      if (command == '3') {
        this.exit()
      } else {
        this.toPerson(command)
      }
    },
    handleCommand1(command) {
      if(!localStorage.getItem('firstToggle')){
         this.$confirm('切换城市后，套餐展示结果将有所变化！', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '关闭',
        }).then(() => {
          let loading = this.getLoading()
          this.togCity(command.id, command.name)
          localStorage.setItem('firstToggle',true)
          loading.close()
        }).catch(() => {
        });
      }else {
        let loading = this.getLoading()
        this.togCity(command.id, command.name)
        localStorage.setItem('firstToggle',true)
        loading.close()
      }
    },
    handleClose(done) {
      this.setFlag(true)
      this.registerShow = 'forget'
      this.registerShow = 'login'
      this.setDialogClose(false)
      this.title = '登录国科学院'
      // done();
    },
    // 跳转到开班计划
    goPlanClass(){
      this.headIndex = 'classPlan'
      this.$router.push('/classList')
      // if(this.isLogin){
      //   this.$router.push('/classList')
      //   return
      // }
      // this.$alert('登录后才可以报名哟!', '提示', {
      //   confirmButtonText: '立即登录',
      //   showClose: true,
      //   callback: action => {
      //     if (action == 'confirm') {
      //       setTimeout(() => {
      //         this.setDialogClose(true)
      //       }, 400);
      //     }
      //   }
      // });
    },
    ...mapMutations([
      'setCityList'
    ]),
    ...mapActions([
      "setCity",
      'setUser',
      'setFlag',
      'setSupplyflag',
      'setDialogClose',
      'setSeivicePhone',
      'setResultCourse'
    ]),
    toPerson(flag) {
      this.headIndex = 'undefine'
      this.setSupplyflag(0);
      this.$router.push({ path: '/personal', query: { flag: flag } })
    },
    /*获取城市列表*/
    getCity() {
      Promise.resolve().then(() => {
        opreate.city().then(res => {
          let curCity = solve()
          this.setCityList(res)
          for (let i in res.cityList) {
            if (curCity == res.cityList[i].cityName) {
              res.cityList[i].flag = true
              if (this.cityName == '') {
                this.togCity(res.cityList[i].id, curCity)
              }
            }
          }
          this.city = res.cityList;
          this.setSeivicePhone(this.cityId)
        })
      }).then(() => {
        this.getData()
      })

    },
    /*切换城市列表*/
    togCity(id, name) {
      let city = {
        'id': id,
        'name': name
      }
      // http://localhost:8081/directionCourse?direction=1&type=&cityId=1
      // if (this.currentUser && this.currentUser.type == '0') {
      //   opreate.updateCity(id, '0', this.currentUser.cluesOrStuId).then(res => {
      //     if (res.code == '0') {
      //       this.setCity(city)
      //     }
      //   })
      // } else {
      //   this.setCity(city)
      // }
      this.setCity(city)

      // 切换城市  更改全部套餐/ICT链接
      var direction=this.GetQueryString('direction');
      if(direction){
        this.$router.push({path: '/directionCourse', query: {direction:direction,type:'',cityId:id}})
      }
    },
    dialogS() {
      this.dialogShow('register')
    },
   GetQueryString(name)
    {
        var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
        var href=decodeURI(window.location.search)
        var r = href.substr(1).match(reg);
        if(r!=null)return  unescape(r[2]); return null;
    },
    dialogShow(type, isShow) {
      let protitle = null
      switch (type) {
        case "login":
          protitle = "登录国科学院"
          break
        case "register":
          protitle = "注册国科学院账号"
          break
        default:
          protitle = "短信重置密码"
          break
      }
      this.setDialogClose(true)
      this.dialogVisible = isShow || true
      this.registerShow = type || 'forget'
      this.title = protitle
    },
    checkMessage(){
      opreate.findGmessageList(0,6,this.currentUser.account,0,0).then(res=>{
        this.messageList=res.data.gmessageList
        this.unreadmesNumber=res.data.unreadNumber
        // console.log(this.unreadmesNumber)
      })
    }
  },
  watch: {
    title() {
      if (this.title == '绑定手机号') {
        this.registerStep = 'register'
      } else {
        this.registerStep = 'login'
      }
    },
    async  cityId() {
      await this.getData()
      await this.querySearch(this.state2)
      this.setResultCourse(this.results)
    },
    searchFlag(){
      if(this.state1 != ''){
        this.state2 = this.state1
      }
      if(!this.searchFlag){
        this.state1 = ''
      }
    },
    // currentUser(e){
    //   if(!this.currentUser.photo){
    //     this.currentUser.photo = '';
    //     return
    //   }
    //   let patt1 = new RegExp("http");
    //   let resultA = patt1.test(this.currentUser.photo);
    //   if(!resultA){
    //     this.currentUser.photo = 'static' + this.currentUser.photo
    //   }
    // },
    searchValue(e){
      if(e == true){
        this.searchFlag = e
      }
    },
    unreadNumber(newVal,oldVal){
            // console.log(newVal)
            if(newVal){
                this.unreadmesNumber=newVal
            }else{
                this.unreadmesNumber=this.unreadNumber
            }
    }
  }
}
</script>

<style scoped lang="stylus" rel="stylesheet/stylus">
@import '~style/base.styl';
.searchBox
  display inline-block
  float right
  transform translateX(-270px)
  @media (min-width: 1920px)
    transform translateX(-190px)
  .widths
    width 380px
    animation bounce .3s ease-out
@keyframes bounce{
  0%{
    width 0px
  }
  50%{
    width 200px
  }
  100%{
    width 380px
  }
}
  .inline-input
    padding-top 10px
    .el-input__inner
      border none

.slide-fade-search-enter-active,.slide-fade-input-enter-active {
  transition: all .3s cubic-bezier(1.0, 0.5, 0.8, 1.0);
}
.slide-fade-search-leave-active,.slide-fade-input-leave-active {
  transition: all .15s ease;
}
.slide-fade-search-enter, .slide-fade-search-leave-to
  transform: translateX(-10px);
  opacity: 0;
.slide-fade-input-enter, .slide-fade-input-leave-to
  transform: translateX(100px);
  opacity: 0;

.searchCourse
  float: right;
  line-height: 64px;
  margin-right 40px
  cursor pointer
  &:hover
    i::before
      color $color-theme
.searchClose
  font-size 12px
  cursor pointer
  &:hover
    i::before
      color $color-theme

.searchNewsz
   float: right;
   position:relative;
   padding-bottom:10px
  .searchNews
    cursor:pointer;
    display:flex;
    margin-right: 12px
    .newsIcon
      margin-right: 2px;
      margin-top: 22px;
      width:16px;
      height:18px;
    .newsNumber
      height:15px;
      padding:0 5px;
      background:rgba(255,98,82,1);
      border-radius:2px;
      margin-top: 20px;
      font-size:12px;
      font-family:MicrosoftYaHei-Bold;
      font-weight:bold;
      color:rgba(255,255,255,1);
      text-align:center
  .newsFrame
      display:none;
      position:absolute;
      -webkit-box-shadow: 0px 0px 12px rgba(0,0,0,0.14);
      box-shadow: 0px 0px 12px rgba(0,0,0,0.14);
      width:372px;
      background:rgba(255,255,255,1);
      border-radius:12px;
      right: -180px;
      top: 50px;
      .unreadNews
        height: 40px;
        border-bottom: 1px solid #EEEEEE;
        line-height: 40px;
        text-indent: 27px;
        font-size: 14px;
        font-family: MicrosoftYaHeiUI;
        font-weight: 400;
        color: rgba(118,118,118,1);
        cursor:pointer
        span
          color:#F73C28
      .newsList
        border-bottom: 1px solid #eee;
        font-size:14px;
        font-family:MicrosoftYaHeiUI;
        font-weight:400;
        color:rgba(32,32,32,1);
        margin-left:27px
        p
          line-height: 32px;
          width: 319px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          cursor:pointer
          &:before
            content:''
            width:6px;
            height:6px;
            background:rgba(255,98,82,1);
            border-radius:50%;
            display:inline-block;
            vertical-align: middle;
            margin-right: 5px;
          &:hover
            color:#F73C28
      .checkAll
        height: 41px;
        line-height: 41px;
        text-align: center;
        font-size: 14px;
        font-family: MicrosoftYaHeiUI;
        font-weight: 400;
        color: rgba(118,118,118,1);
        cursor:pointer
        &:hover
          color:#F73C28


.searchNewsz:hover
  display:block
.searchNewsz:hover .newsFrame
  display:block

.leftImg, .rightCon {
  display: inline-block;
}

.logo {
  position: relative;
  display: inline;
  .collegeText{
    position: absolute;
    z-index: -999;
    color: transparent;
  }
}
.icon-xiaosan_n
  display: inline-block;
  transform: scale(0.7);
.icon-xiaosan_n::before
  margin-left 5px

.backLogin {
  font-size: 10px;
  margin-left: 20px;
}

.personInfo {
  background: $color-text;
  width: 148px;
  height: 200px;
  background: rgba(255, 255, 255, 1);
  border-radius: 12px;
  box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.14);
  position: absolute;
  z-index: 30;
  right: 0;
  padding: 12px 0;
  border: none;
  @extend .borderBox;

  .myInfo, .myOrder, .exit {
    font-size: $font-size-medium;
    color: #202020;
    text-align: left;
    height: 44px;
    line-height: 44px;
    cursor: pointer;
    padding: 0 20px;

    &:hover {
      background: $color-theme;
      color: $color-text;
    }
  }
  .myCourse {
    font-size: $font-size-medium;
    color: #202020;
    text-align: left;
    height: 44px;
    line-height: 44px;
    cursor: pointer;
    padding: 0 20px;

    &:hover {
      background: $color-theme;
      color: $color-text;
    }
  }

  .exit {
    /* border-radius: 0 0 12px 12px; */
    line-height: 44px;
  }
}

.headBox {
  position: absolute;
  z-index: 30;
  @extend .sWidth;
}

.personHover {
  float: right;
}

.myperson {
  line-height: 24px;
  width: 80px;
  font-size: 12px;
  text-align: center;
  color: $color-text-mt;
  border-radius: 12px;
  cursor: pointer;
  display: inline-block;
  height: 24px;
  margin-top: 20px;
  margin-bottom: 8px;

  &:hover {
    color: $color-theme;

    i::before {
      color: $color-theme;
    }
  }
}

.register {
  position: absolute;
  top: 28px;
  font-size: $font-size-medium-x;
  color: $color-text-mt;
  right: 28px;
  cursor: pointer;
}

.header {
  width: 100%;
  background: $color-text;
  height: 64px;
}

.fix {
  position: fixed;
  top: 0;
  z-index: 1999;
  width: 100vw;
  background: $color-text;
  left: 0;
  box-shadow: 4px 0px 12px rgba(0, 0, 0, 0.12);
}

.headContent {
  @extend .sWidth, .borderBox;

  img {
    margin-top: 17px;
    float: left;
    margin-right: 20px;
    cursor: pointer;
  }

  .el-message-box__wrapper .el-message-box .el-message-box__btns span {
    background: transparent;
  }
}

.location {
  cursor: pointer;
}

.headBtn {
  float: right;

  span {
    line-height: 32px;
    color: $color-text-m;
    font-size: $font-size-medium;
    cursor: pointer;
    margin-left: 20px;
    margin-top: 14px;
    width: 72px;
    height: 32px;
    text-align: center;
    color: $color-text-mt;
    border-radius: 16px;
    display: inline-block;
    border: 1px solid $color-btn-border;

    &:hover {
      background: $color-theme;
      color: $color-text;
      border: 1px solid $color-theme;
    }
  }

  span:first-child {
    background: $color-theme;
    color: $color-text;
    border: 1px solid $color-theme;

    &:hover {
      background: $color-background-more;
    }
  }
}

.headLoc {
  display: inline-block;
  line-height: 64px;
  font-size: $font-size-medium;
  margin: 0 110px;
  color: $color-text-mt;
  cursor: pointer;
  margin-bottom: -12px;

  &:hover {
    color: $color-theme;

    i::before {
      color: $color-theme;
    }
  }

  i {
    margin-right: 10px;
  }
}

.locActive {
  color: $color-theme !important;

  i::before {
    color: $color-theme;
  }
}

.headNav {
  display: inline-block;
  line-height: 64px;
  font-size: $font-size-medium;

  span {
    cursor: pointer;
    margin-right: 50px;
    color: $color-text-mt;

    &:hover {
      color: $color-theme;
    }
  }

  .headActive {
    color: $color-theme;
    font-weight: bold;
  }
}

.cityMsg {
  border: none;
  width: 148px;
  // height: 200px;
  padding-bottom:10px;
  background: rgba(255, 255, 255, 1);
  border-radius: 12px;
  box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.14);
  display: inline-block;
  background: #ffffff;
  /* position: absolute; */
  /* left: 300px; */
  z-index: 30;
  padding-top: 12px;
  @extend .borderBox;

  .cities {
    font-size: 14px;
    /* margin-top: 12px; */
    cursor: pointer;
    display: inline-block;
    width: 100%;
    padding-left: 20px;
    float: left;
    height: 44px;
    line-height: 44px;

    &:hover {
      background: $color-theme;
      color: $color-text;
    }
  }

  .cities>span {
    color: $color-theme;
  }
}
</style>
